package 集合;

import java.util.HashSet;
import java.util.Objects;

/**
 * @ClassName : HashSetText
 * @Author : LV88VL
 * @Date: 2021/3/11 16:24
 * @Description : HashSet接口
 *                          存储元素时，是先调用元素对象的hashCode()方法，而每个学生都是新建立
 *                          的对象，所以对应的哈希值都不相同，不需要通过equals来进一步判断
 *                          但是存在不同对象存在同一学生的情况，这时就需要对hashCode方法进行重写
 *                          如果哈希值相同，在通过equals方法来判断
 */
public class HashSetText {
    public static class Student{
        private String name;
        private int age;
        Student(){

        }
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }

        @Override
        public boolean equals(Object o) {
            System.out.println("调用了equals方法");
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Student student = (Student) o;
            return age == student.age && Objects.equals(name, student.name);
        }

        @Override
        public int hashCode() {
            System.out.println("调用了hashCode方法");
            return Objects.hash(name, age);
        }
    }

    public static void main(String[] args) {
        Student s1 =new Student("张三",5);
        Student s2 =new Student("李四",55);
        Student s3 =new Student("张三",5);
        Student s4 =new Student("赵六",115);
        HashSet<Student> hs =new HashSet<>();
        HashSet<Student> s5 =new HashSet<>();
        //哈希值不相同，但是equals（）比较可能相同的情况
        hs.add(s1);
        hs.add(s2);
        hs.add(s3);
        hs.add(s4);
        //哈希值相同，但是equals()比较不相同的情况
        s5.add(new Student("拉拉",12));
        s5.add(new Student("帕帕",12));
        for (Student st : hs){
            System.out.println(st.getName()+"=="+st.getAge());
        }
        for (Student stt:s5){
            System.out.println(stt.getName()+"=="+stt.getAge());
        }
    }
}
